<script setup>
import {onMounted, ref, reactive} from 'vue';
import {Delete, EditPen, Plus, Refresh, RefreshRight, Upload, UploadFilled} from "@element-plus/icons-vue";
import {queryUserById, queryUserPage} from '@/api/user/user.js';
import UserDialogForm from './components/UserDialogForm.vue';
import UserSearchForm from './components/UserSearchForm.vue';
import UserTable from './components/UserTable.vue';

// 表单参数
const queryForm = ref({
  page: 1,
  pageSize: 5,
  total: 0,
  pages: 1,
  body: {
    username: '',
    name: '',
  }
});

// 初始化性别列表
const genderList = [
  {label: '男', value: '1'},
  {label: '女', value: '2'}
];

// 数据列表
const userList = ref([]);

// 弹框控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加员工');

// 表单数据
const formData = reactive({
  username: '',
  name: '',
  gender: '',
  phone: '',
  role: '',
  status: '',
});

// 定义方法，实现分页查询
const queryUsers = async () => {
  let result = await queryUserPage(queryForm.value);
  userList.value = result.data;
  queryForm.value.pages = result.pages;
  queryForm.value.total = result.total;
};

// 分页调用
const handleSizeChange = (val) => {
  queryForm.value.pageSize = val;
  queryForm.value.page = 1;
  queryUsers();
};

const handleCurrentChange = (val) => {
  queryForm.value.page = val;
  queryUsers();
};

// 清空搜索表单
const clear = () => {
  Object.keys(queryForm.value.body).forEach(key => queryForm.value.body[key] = '');
  queryUsers();
};

// 展示弹框
const showDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = '添加员工';
  resetForm();
};

const resetForm = () => {
  Object.keys(formData).forEach(key => formData[key] = '');
};

// 通过id查询员工数据
const queryById = async (row) => {
  let result = await queryUserById(row.id);
  Object.assign(formData, result.data);
  dialogVisible.value = true;
  dialogTitle.value = '修改员工';
};

// 初始化调用
onMounted(() => {
  queryUsers();
});
</script>

<template>
  用户列表
  <br/>
  <br/>
  <el-button :icon="Plus" @click="showDialog"></el-button>
  <el-button :icon="RefreshRight"></el-button>
  <el-button :icon="Upload"></el-button>
  <el-button :icon="UploadFilled"></el-button>
  <el-button :icon="Refresh"></el-button>

  <UserDialogForm
      :dialogVisible="dialogVisible"
      @update:dialogVisible="val => dialogVisible = val"
      :title="dialogTitle"
      :formData="formData"
      :genderList="genderList"
      @refresh="queryUsers"
  />

  <UserSearchForm
      :queryForm="queryForm"
      @search="queryUsers"
  />

  <UserTable
      :userList="userList"
      :queryForm="queryForm"
      @edit="queryById"
      @delete="queryUsers"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<style scoped>
.el-button {
  border: 1px solid #dcdfe6;
  width: 15px;
  border-radius: 100%;
  box-shadow: 0 5px 5px #dcdfe6;
}

.el-button:hover {
  background-color: #f6f6f6;
}
</style>